package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;

    /**
     * 根据id查询商铺
     *
     * @param id 商铺id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        // 解决缓存穿透
//        Shop shop = cacheClient
//                .queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 互斥锁解决缓存击穿
        // Shop shop = cacheClient
        //         .queryWithMutex(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 逻辑过期解决缓存击穿
         Shop shop = cacheClient
                 .queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);

        if (shop == null) {
            return Result.fail("商铺信息为空");
        }
        return Result.ok(shop);
    }

    /**
     * 解决缓存击穿（互斥锁）
     *
     * @param id
     * @return
     */
    private Shop queryWithMutex(Long id) {
        //1.从redis中查询
        String cacheShopKey = CACHE_SHOP_KEY + id;
        String shopCacheInfo = stringRedisTemplate.opsForValue().get(cacheShopKey);
        //2.存在 直接返回
        if (StrUtil.isNotBlank(shopCacheInfo)) {
            Shop shopInfo = JSONUtil.toBean(shopCacheInfo, Shop.class);
            return shopInfo;
        }
        if (shopCacheInfo != null) {
            //是空值
            return null;
        }
        //3实施缓存重建
        //3.1.获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            //3.2.判断是否获取成功
            if (!isLock) {
                //3.3.失败 则休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //获取锁成功 应该再次检测redis中有无缓存 如果已有 则无需重建缓存
            String shopCacheInfo2 = stringRedisTemplate.opsForValue().get(cacheShopKey);
            //2.存在 直接返回
            if (StrUtil.isNotBlank(shopCacheInfo2)) {
                Shop shopInfo = JSONUtil.toBean(shopCacheInfo2, Shop.class);
                return shopInfo;
            }
            //3.4.获取锁成功且缓存中不存在 则根据id从数据库中查询，进行缓存重建
            shop = getById(id);
            //模拟查询数据库延迟
            Thread.sleep(200);
            //4.数据库中不存在 返回错误信息
            if (shop == null) {
                //将空值也写回redis 预防缓存穿透
                stringRedisTemplate.opsForValue().set(cacheShopKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //5.数据中存在 返回信息 并写回redis 设置过期时间为30分钟
            stringRedisTemplate.opsForValue().set(cacheShopKey, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL
                    , TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //6.释放互斥锁
            unLock(lockKey);
        }
        return shop;
    }

    /**
     * 解决缓存击穿（利用逻辑过期时间）
     *
     * @param id
     * @return
     */
    private Shop queryWithLogicalExpire(Long id) {
        //1.从redis中查询
        String cacheShopKey = CACHE_SHOP_KEY + id;
        String shopCacheInfo = stringRedisTemplate.opsForValue().get(cacheShopKey);
        //2.不存在 直接返回
        if (StrUtil.isBlank(shopCacheInfo)) {
            return null;
        }
        //3.命中则判断缓存是否过期
        //  将json数据反序列化为java对象
        RedisData redisData = JSONUtil.toBean(shopCacheInfo, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();//逻辑过期时间
        //4.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期 直接返回商铺信息
            return shop;
        }
        //5.已过期 需要缓存重建
        //6实施缓存重建
        //6.1.获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            //获取锁成功再次判断redis缓存是否过期 如果过期则缓存重建
            //4.判断是否过期
            if (expireTime.isAfter(LocalDateTime.now())) {
                //未过期 直接返回商铺信息
                return shop;
            }
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                //重建缓存
                try {
                    this.saveShopToRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        //返回过期的商铺信息
        return shop;
    }


    /**
     * 解决缓存穿透
     * @param id
     * @return
     */
    private Shop queryWithPassThrough(Long id) {
        //1.从redis中查询
        String cacheShopKey = CACHE_SHOP_KEY+ id;
        String shopCacheInfo = stringRedisTemplate.opsForValue().get(cacheShopKey);
        //2.存在 直接返回
        if (StrUtil.isNotBlank(shopCacheInfo)){
            Shop shopInfo = JSONUtil.toBean(shopCacheInfo, Shop.class);
            return shopInfo;
        }
        if(shopCacheInfo!=null){
            //是空值
            return null;
        }
        //3.不存在 从数据库中查询
        Shop shop = getById(id);
        //4.数据库中不存在 返回错误信息
        if(shop==null){
            //将空值也写回redis 预防缓存穿透

            stringRedisTemplate.opsForValue().set(cacheShopKey,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //5.数据中存在 返回信息 并写回redis 设置过期时间为30分钟
        stringRedisTemplate.opsForValue().set(cacheShopKey,JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL
        , TimeUnit.MINUTES);
        return shop;
    }

    /**
     * 更新商铺信息
     * @param shop
     * @return
     */
    @Transactional
    @Override
    public Result updateShopInfo(Shop shop) {
        Long shopId = shop.getId();
        if(shopId==null){{
            return Result.fail("更新失败");
        }}
        //更新数据库
        updateById(shop);
        //删除缓存
        String shopKey = CACHE_SHOP_KEY + shopId;
        stringRedisTemplate.delete(shopKey);
        return Result.ok();
    }

    /**
     * 根据地理位置查询商铺
     * @param typeId 类别id
     * @param current 当前页码
     * @param x
     * @param y
     * @return
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1.是否需要更具坐标查询
        if(x==null||y==null){
            //不需要坐标查询 直接查询数据库
            Page<Shop> page = query().eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //2. 计算分页参数
        int from = (current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current*SystemConstants.DEFAULT_PAGE_SIZE;
        String key = RedisConstants.SHOP_GEO_KEY+typeId;
        //3.查询redis 按照距离排序 分页 结果：shopId distance GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if(geoResults == null){
            return Result.ok(Collections.emptyList());
        }
        //4.解析出id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = geoResults.getContent();
        if(from>= content.size()){
            //后面没有数据 直接返回
            return Result.ok(Collections.emptyList());
        }
        //4.1 截取from - end 的部分
//        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> geoResults1 = content.subList(from, end);
        List<Long> shopIdList = new ArrayList<>(content.size());
        Map<String,Distance> distanceMap = new HashMap<>(content.size());
        content.stream().skip(from).forEach(result->{//skip跳过前from个
            //4.2 获得店铺id
            String shopId = result.getContent().getName();
            shopIdList.add(Long.valueOf(shopId));
            //4.3 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopId,distance);
        });
        //5.根据id查询shop
        String idStr = StrUtil.join(",", shopIdList);
        List<Shop> shopList = query().in("id", shopIdList).last("order by field(id," + idStr + ")").list();
        shopList.forEach(shop -> {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        });
        return Result.ok(shopList);
    }

    /**
     * 设置逻辑过期时间的缓存预热
     * @param id 商铺id
     * @param expireSeconds 逻辑过期时间
     */
    public void saveShopToRedis(Long id,Long expireSeconds){
        //1.查询店铺数据
        Shop shop = getById(id);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);

    }
    private void unLock(String key){
        stringRedisTemplate.delete(key);

    }
}
